# Default file for directory requests
DirectoryIndex index.php index.html

# Enable RewriteEngine
RewriteEngine On

# Allow service worker and manifest to be served directly
RewriteRule ^sw\.js$ - [L]
RewriteRule ^manifest\.php$ - [L]
RewriteRule ^offline\.html$ - [L]

# Service Worker headers
<FilesMatch "sw\.js$">
    <IfModule mod_headers.c>
        Header set Service-Worker-Allowed "/"
        Header set Cache-Control "no-cache, no-store, must-revalidate"
    </IfModule>
</FilesMatch>

# Force HTTPS redirection (disabled for localhost - enable on production)
# RewriteCond %{HTTPS} off [OR]
# RewriteCond %{HTTP:X-Forwarded-Proto} !https
# RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Redirect .php URLs to non-.php URLs (external redirect, GET only)
RewriteCond %{THE_REQUEST} ^GET\s(.+?)\.php[\s?] [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^.*/index\.php$
RewriteCond %{REQUEST_URI} !^.*/ajax/
RewriteRule ^(.+)\.php$ $1 [L,R=301]

# Remove .php extension (internal rewrite)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+?)/?$ $1.php [QSA,L]

# Custom Error Pages
ErrorDocument 400 /errors/400.php
ErrorDocument 401 /errors/401.php
ErrorDocument 403 /errors/403.php
ErrorDocument 404 /errors/404.php
ErrorDocument 500 /errors/500.php
ErrorDocument 502 /errors/502.php
ErrorDocument 503 /errors/503.php

# Prevent directory browsing
Options -Indexes

# Protect sensitive files
<FilesMatch "^(config\.php|\.htaccess|\.env|composer\.json|composer\.lock|package\.json)$">
    Order Allow,Deny
    Deny from all
</FilesMatch>

# Block access to hidden files and directories
<IfModule mod_rewrite.c>
    RewriteCond %{SCRIPT_FILENAME} -d [OR]
    RewriteCond %{SCRIPT_FILENAME} -f
    RewriteRule "(^|/)\." - [F]
</IfModule>

# Protect database files
<FilesMatch "\.(sql|db|sqlite|sqlite3)$">
    Order Allow,Deny
    Deny from all
</FilesMatch>

# Security Headers
<IfModule mod_headers.c>
    Header set X-Content-Type-Options "nosniff"
    Header set X-Frame-Options "SAMEORIGIN"
    Header set X-XSS-Protection "1; mode=block"
    Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

# Enable Compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
</IfModule>

# Browser Caching
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType text/javascript "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType text/html "access plus 0 seconds"
</IfModule>